package com.mx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mx.mapper.*;
import com.mx.pojo.*;
import com.mx.pojo.VO.ArticleVO;
import com.mx.utils.QiNiuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Controller
public class IndexController {

    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    StarMapper starMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    TagMapper tagMapper;
    @Autowired
    ArticleTagMapper articleTagMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    AttentionMapper attentionMapper;

    @GetMapping("/test1")
    public String test1() {
        return "test1";
    }

    @GetMapping("/test2")
    public String test2(Integer id, Model model) {
        model.addAttribute("id", id);
        return "test2";
    }

    @GetMapping("/test")
    public String forUsername() {
        return "test";
    }

    @PostMapping("/test")
    @ResponseBody
    public String test(@RequestParam("file") MultipartFile file) throws IOException {
        // 获取文件的名称
        String fileName = file.getOriginalFilename();

        // 使用工具类根据上传文件生成唯一图片名称
        String imgName = UUID.randomUUID().toString() + fileName;

        if (!file.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            String path = QiNiuUtil.uploadQNImg(inputStream, imgName);
            System.out.print("七牛云返回的图片链接:" + path);
            return path;
        }
        return "上传失败";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String register1() {
        return "register";
    }

    @GetMapping("/search")
    public String search(String keyword,Integer id,Model model,HttpSession session) {
        if (id == null)
            id = 1;

        List<Tag> tags = tagMapper.selectList(null);
        model.addAttribute("tags", tags);

        ArrayList<ArticleVO> articleVOS = new ArrayList<>();

        //分页
        Page<Article> objectPage = new Page<>(id, 5);
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.like("title",keyword);
        articleQueryWrapper.orderByDesc("id");
        Page<Article> articlePage = articleMapper.selectPage(objectPage, articleQueryWrapper);
        List<Article> articles = articlePage.getRecords();

        for (Article article : articles) {
            if (article.getContent().length() >= 221) {
                article.setContent(article.getContent().substring(0, 220) + "...");
            }
            User user = userMapper.selectById(article.getUid());
            articleVOS.add(new ArticleVO(article, user.getName()));
        }

        //如果已经登录  点赞收藏情况查询
        User user1 = (User) session.getAttribute("user");
        if (user1 != null) {
            for (ArticleVO articleVO : articleVOS) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("uid", user1.getId());//     我
                map.put("aid", articleVO.getId());//关注的文章
                List<Star> stars = starMapper.selectByMap(map);
                if (stars != null && stars.size() != 0) {
                    Star star = stars.get(0);
                    if (star.getStar() != 0) {
                        articleVO.isStar = true;

                    }
                    if (star.getAgree() != 0) {
                        articleVO.isAgree = true;
                    }
                }
            }
        }

        model.addAttribute("articles", articleVOS);
        model.addAttribute("articlePage", articlePage);
        model.addAttribute("keyword", keyword);
        return "search";
    }


    @PostMapping("/register")
    public String register(String username, String password, String name,HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        List<User> users = userMapper.selectByMap(map);
        //数据库已有该用户名  注册失败
        if (users != null && users.size() != 0) {
            return "redirect:/register?register=false";
        }
        //登录成功
        User user = new User();
        user.setId(0);
        user.setName(name);
        //默认用户头像
        user.setAvatar("https://pic1.zhimg.com/da8e974dc_is.jpg");
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insert(user);
        return "redirect:/login";
    }

    @PostMapping("/admin")
    public String admin(String username, String password, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        List<User> users = userMapper.selectByMap(map);
        //登录成功
        if (users != null && users.size() != 0) {
            //登录信息存入session中  标志已经登录
            System.out.println("session登录对象 " + users.get(0) + " " + session);
            session.setAttribute("user", users.get(0));
            return "redirect:/";
        }
        //登录失败
        return "redirect:/login?pass=false";
    }

    @RequestMapping("/sort")
    public String sort(Integer tid, Model model) {
        List<Tag> tags = tagMapper.selectList(null);
        model.addAttribute("tags", tags);
        QueryWrapper<ArticleTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tid", tid);
        List<ArticleTag> articleTags = articleTagMapper.selectList(queryWrapper);
        ArrayList<ArticleVO> articleVOS = new ArrayList<>();

        List<Article> articles = new ArrayList<>();
        for (ArticleTag articleTag : articleTags) {
            articles.add(articleMapper.selectById(articleTag.getAid()));
        }

        for (Article article : articles) {
            if (article.getContent().length() >= 221) {
                article.setContent(article.getContent().substring(0, 220) + "...");
            }
            User user = userMapper.selectById(article.getUid());
            articleVOS.add(new ArticleVO(article, user.getName()));
        }
        Collections.reverse(articleVOS);
        model.addAttribute("articles", articleVOS);
        return "sort";
    }

    @RequestMapping("/")
    public String dashboard(Integer id, Model model, HttpSession session) {
        if (id == null)
            id = 1;

        List<Tag> tags = tagMapper.selectList(null);
        model.addAttribute("tags", tags);

        ArrayList<ArticleVO> articleVOS = new ArrayList<>();

        //分页
        Page<Article> objectPage = new Page<>(id, 5);
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.orderByDesc("id");
        Page<Article> articlePage = articleMapper.selectPage(objectPage, articleQueryWrapper);
        List<Article> articles = articlePage.getRecords();

        for (Article article : articles) {
            if (article.getContent().length() >= 221) {
                article.setContent(article.getContent().substring(0, 220) + "...");
            }
            User user = userMapper.selectById(article.getUid());
            articleVOS.add(new ArticleVO(article, user.getName()));
        }

        //如果已经登录  点赞收藏情况查询
        User user1 = (User) session.getAttribute("user");
        if (user1 != null) {
            for (ArticleVO articleVO : articleVOS) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("uid", user1.getId());//     我
                map.put("aid", articleVO.getId());//关注的文章
                List<Star> stars = starMapper.selectByMap(map);
                if (stars != null && stars.size() != 0) {
                    Star star = stars.get(0);
                    if (star.getStar() != 0) {
                        articleVO.isStar = true;

                    }
                    if (star.getAgree() != 0) {
                        articleVO.isAgree = true;
                    }
                }
            }
        }

        model.addAttribute("articles", articleVOS);
        model.addAttribute("articlePage", articlePage);
        return "dashboard";
    }
    @RequestMapping("/hot")
    public String hot(Integer id, Model model, HttpSession session) {
        if (id == null)
            id = 1;

        List<Tag> tags = tagMapper.selectList(null);
        model.addAttribute("tags", tags);

        ArrayList<ArticleVO> articleVOS = new ArrayList<>();

        //分页
        Page<Article> objectPage = new Page<>(id, 5);
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.orderByDesc("agree");
        Page<Article> articlePage = articleMapper.selectPage(objectPage, articleQueryWrapper);
        List<Article> articles = articlePage.getRecords();

        for (Article article : articles) {
            if (article.getContent().length() >= 221) {
                article.setContent(article.getContent().substring(0, 220) + "...");
            }
            User user = userMapper.selectById(article.getUid());
            articleVOS.add(new ArticleVO(article, user.getName()));
        }

        //如果已经登录  点赞收藏情况查询
        User user1 = (User) session.getAttribute("user");
        if (user1 != null) {
            for (ArticleVO articleVO : articleVOS) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("uid", user1.getId());//     我
                map.put("aid", articleVO.getId());//关注的文章
                List<Star> stars = starMapper.selectByMap(map);
                if (stars != null && stars.size() != 0) {
                    Star star = stars.get(0);
                    if (star.getStar() != 0) {
                        articleVO.isStar = true;

                    }
                    if (star.getAgree() != 0) {
                        articleVO.isAgree = true;
                    }
                }
            }
        }

        model.addAttribute("articles", articleVOS);
        model.addAttribute("articlePage", articlePage);
        return "hot";
    }


    @RequestMapping("/detail")
    public String detail(Integer id, Model model,HttpSession session) {
        if (id == null)
            id = 1;
        Article article = articleMapper.selectById(id);
        User user = userMapper.selectById(article.getUid());
        ArticleVO articleVO = new ArticleVO(article, user.getName());

        //如果已经登录  点赞收藏情况查询
        User user1 = (User) session.getAttribute("user");
        if (user1 != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid", user1.getId());//     我
            map.put("aid", articleVO.getId());//关注的文章
            List<Star> stars = starMapper.selectByMap(map);
            if (stars != null && stars.size() != 0) {
                Star star = stars.get(0);
                if (star.getStar() != 0) {
                    articleVO.isStar = true;

                }
                if (star.getAgree() != 0) {
                    articleVO.isAgree = true;
                }
            }
        }
        model.addAttribute("article", articleVO);

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("aid", id);
        List<Comment> comments = commentMapper.selectList(commentQueryWrapper);
        model.addAttribute("comments", comments);
        model.addAttribute("avatar", user.getAvatar());

        return "detail";
    }

    //进入个人主页
    @RequestMapping("/manage")
    public String manage(Integer id, Integer uid, Model model, HttpSession session) {
        //id为页数
        if (id == null)
            id = 1;
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);//作者为当前作者
        //分页
        Page<Article> objectPage = new Page<>(id, 3);
        queryWrapper.orderByDesc("id");
        Page<Article> articlePage = articleMapper.selectPage(objectPage, queryWrapper);
        //查出uid的作者的文章
        List<Article> articles = articlePage.getRecords();

        ArrayList<ArticleVO> articleVOS = new ArrayList<>();
        for (Article article : articles) {
            if (article.getContent().length() >= 141) {
                article.setContent(article.getContent().substring(0, 140) + "...");
            }
            User user = userMapper.selectById(article.getUid());
            articleVOS.add(new ArticleVO(article, user.getName()));
        }
        //如果已经登录  点赞收藏情况查询

        boolean guanzhu=false;
        User user1 = (User) session.getAttribute("user");
        if (user1 != null) {
            //是否关注当前作者
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("masteruid",user1.getId());
            map1.put("doneuid",uid);
            List<Attention> attentions = attentionMapper.selectByMap(map1);
            if(attentions!=null&&attentions.size()!=0)
            {
                guanzhu=true;
            }


            for (ArticleVO articleVO : articleVOS) {

                HashMap<String, Object> map = new HashMap<>();
                map.put("uid", user1.getId());//     我
                map.put("aid", articleVO.getId());//关注的文章
                List<Star> stars = starMapper.selectByMap(map);
                if (stars != null && stars.size() != 0) {
                    Star star = stars.get(0);
                    if (star.getStar() != 0) {
                        articleVO.isStar = true;

                    }
                    if (star.getAgree() != 0) {
                        articleVO.isAgree = true;
                    }
                }
            }
        }
        int dianzanshu=0;
        HashMap<String, Object> map6 = new HashMap<>();
        map6.put("uid",uid);
        List<Article> articles1 = articleMapper.selectByMap(map6);
        for (Article article : articles1) {
            dianzanshu+=article.getAgree();
        }

        int guanzhushu=0;
        HashMap<String, Object> map5 = new HashMap<>();
        map5.put("doneuid",uid);
        List<Attention> attentions = attentionMapper.selectByMap(map5);

        //点赞数和收藏数
        model.addAttribute("dianzanshu",dianzanshu);
        model.addAttribute("guanzhushu",attentions.size());



        model.addAttribute("guanzhule",guanzhu);
        //传user对象过去
        User user = userMapper.selectById(uid);
        model.addAttribute("name", user.getName());
        model.addAttribute("avatar", user.getAvatar());
        model.addAttribute("uid", user.getId());
        model.addAttribute("introduction", user.getIntroduction());

        model.addAttribute("articles", articleVOS);
        model.addAttribute("articlePage", articlePage);
        return "manage";
    }

    //退出
    @RequestMapping("/exit")
    public String exit(HttpSession session, Integer uid, Model model) {
        User user = (User) session.getAttribute("user");
        if (user != null)
            session.removeAttribute("user");
        return "redirect:/";
    }
}
